import 'dart:async';
import 'dart:io';

import 'package:alipay_kit/alipay_kit_platform_interface.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:tracker/common/constants/app_constants.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/pay/model/order_info_req.dart';
import 'package:tracker/common/pay/model/order_info_resp.dart';
import 'package:tracker/utils/toast_utils.dart';

import 'model/alipay_order_info.dart';

class AliPayUtils {
  late final StreamSubscription<AlipayResp> _paySubs;
  final AlipayKitPlatform _alipay = AlipayKitPlatform.instance;

  void listenPay(void Function(AlipayResp resp) callback) async {
    // 判断是否安装支付宝
    final bool isInstalled = await _alipay.isInstalled();
    if (!isInstalled) {
      // ToastUtils.showToast('请先安装支付宝');
      return;
    }
    _paySubs = _alipay.payResp().listen((AlipayResp resp) {
      XLogger.info('支付结果：${resp.resultStatus}');
      callback(resp);
      // if (resp.resultStatus == '9000') {
      //   // 支付成功
      //   print('支付成功');
      // } else {
      //   // 支付失败
      //   print('支付失败');
      // }
    });
  }

  void dispose() {
    try {
      _paySubs.cancel();
    } catch (e) {}
  }

  void createOrder(OrderInfoReq orderInfoReq) async {
    // 判断是否安装支付宝
    final bool isInstalled = await _alipay.isInstalled();
    if (!isInstalled) {
      ToastUtils.showToast('请先安装支付宝');
      return;
    }
    ToastUtils.showLoading();
    final res = await post<OrderInfoResp, OrderInfoResp>('',
        data: orderInfoReq.toJson(), decodeType: OrderInfoResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        // 创建订单成功
        if (Platform.isAndroid) {
          _alipay.setEnv(env: AlipayEnv.online);
        }
        _alipay.pay(orderInfo: resp.data!.body!);
      } else {
        ToastUtils.showToast(resp.msg ?? '创建订单失败');
      }
    }, failure: (String msg, int code) {
      ToastUtils.showToast('创建订单失败');
    });
  }

  void createVip(int? packageId, String imei) async {
    // 判断是否安装支付宝
    final bool isInstalled = await _alipay.isInstalled();
    if (!isInstalled) {
      ToastUtils.showToast('请先安装支付宝');
      return;
    }
    final res = await get<AlipayOrderInfoResp, AlipayOrderInfoResp>(
        "$newBaseULr/ali/appPay?imei=${imei.toString()}&packageId=$packageId",
        decodeType: AlipayOrderInfoResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        // 创建订单成功
        if (Platform.isAndroid) {
          _alipay.setEnv(env: AlipayEnv.online);
        }
        _alipay.pay(orderInfo: resp.data ?? "",dynamicLaunch: true);
      } else {
        ToastUtils.showToast(resp.msg ?? '创建订单失败');
      }
    }, failure: (String msg, int code) {
      ToastUtils.showToast('创建订单失败');
    });
  }
  void createChargeSIMCard(int? packageId, String iccid) async {
    // 判断是否安装支付宝
    final bool isInstalled = await _alipay.isInstalled();
    if (!isInstalled) {
      ToastUtils.showToast('请先安装支付宝');
      return;
    }
    final res = await get<AlipayOrderInfoResp, AlipayOrderInfoResp>(
        "$newBaseULr/sim/ali/appPay?iccid=${iccid}&packageId=$packageId",
        decodeType: AlipayOrderInfoResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        // 创建订单成功
        if (Platform.isAndroid) {
          _alipay.setEnv(env: AlipayEnv.online);
        }
        _alipay.pay(orderInfo: resp.data ?? "",dynamicLaunch: true);
      } else {
        ToastUtils.showToast(resp.msg ?? '创建订单失败');
      }
    }, failure: (String msg, int code) {
      ToastUtils.showToast('创建订单失败');
    });
  }


}
